// Package system
// @Author zhongxc
// @Date 2024/7/22 17:53:00
// @Desc
package system

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"golang.org/x/net/context"
	"net/http"
	"strconv"
	"strings"
	"vben-api/api/rpc"
	"vben-api/api/types"
	"vben-api/pkg/svc"
	common "vben-common"
	"vben-common/errs"
	"vben-common/utils"
	roleServiceV1 "vben-grpc-common/vben-admin/types/role.service.v1"
)

type Role struct {
	svcCtx *svc.ServiceContext
}

func NewRole(svcCtx *svc.ServiceContext) *Role {
	return &Role{
		svcCtx: svcCtx,
	}
}

// GetRoleInfo
// @Description: 角色信息查询
// @receiver r
// @param ctx
func (r *Role) GetRoleInfo(ctx *gin.Context) {
	result := common.NewResult()
	roleIdStr := ctx.Query("roleId")
	fmt.Printf("roleIdStr:%v\n", roleIdStr)
	roleIdInt, err := strconv.ParseInt(roleIdStr, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}
	req := &roleServiceV1.GetRoleRequest{
		Id: roleIdInt,
	}

	info, err := rpc.RoleServiceClient.GetRole(context.Background(), req)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	var roleInfo types.RoleInfo
	_ = copier.Copy(&roleInfo, info)

	ctx.JSON(http.StatusOK, result.Success(roleInfo))
}

func (r *Role) GetRoleList(ctx *gin.Context) {

	result := common.NewResult()

	roleName := ctx.Query("roleName")
	roleStatus, err := strconv.ParseInt(ctx.DefaultQuery("roleStatus", "-1"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}

	list, err := rpc.RoleServiceClient.GetRoleList(context.Background(), &roleServiceV1.RoleListRequest{
		Name:   roleName,
		Status: int32(roleStatus),
	})
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	var roleList = make([]*types.RoleInfo, 0)
	for _, val := range list.Data {
		var roleInfo types.RoleInfo
		_ = copier.Copy(&roleInfo, val)

		menuSlice, _ := utils.StringSliceToIntSlice(strings.Split(val.Menu, ","))
		roleInfo.Menu = menuSlice
		roleList = append(roleList, &roleInfo)
	}

	ctx.JSON(http.StatusOK, result.Success(roleList))
}

func (r *Role) SaveRole(ctx *gin.Context) {
	result := common.NewResult()
	var roleInfo *types.RoleInfo
	if err := ctx.ShouldBind(&roleInfo); err != nil {
		ctx.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}
	menuIds := ctx.PostForm("menu_ids")
	menuIdsSlice, _ := utils.StringSliceToIntSlice(strings.Split(menuIds, ","))

	var roleReq roleServiceV1.CreateRoleRequest
	_ = copier.Copy(&roleReq, roleInfo)
	roleReq.MenuIds = menuIdsSlice

	resp, err := rpc.RoleServiceClient.CreateRole(context.Background(), &roleReq)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}
	ctx.JSON(http.StatusOK, result.Success(resp))
}

func (r *Role) UpdateRole(ctx *gin.Context) {
	result := common.NewResult()
	var roleInfo *types.RoleInfo
	if err := ctx.ShouldBind(&roleInfo); err != nil {
		ctx.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}
	menuIds := ctx.PostForm("menu_ids")
	menuIdsSlice, _ := utils.StringSliceToIntSlice(strings.Split(menuIds, ","))

	var roleReq roleServiceV1.UpdateRoleRequest
	_ = copier.Copy(&roleReq, roleInfo)
	roleReq.MenuIds = menuIdsSlice
	roleReq.UpdatedBy = "Kkk"

	resp, err := rpc.RoleServiceClient.UpdateRole(context.Background(), &roleReq)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}
	ctx.JSON(http.StatusOK, result.Success(resp))
}

func (r *Role) DeleteRole(ctx *gin.Context) {

	result := common.NewResult()

	ids := ctx.PostForm("ids")
	fmt.Println("ids=", ids)
	if len(ids) == 0 {
		ctx.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}

	idSlice := strings.Split(ids, ",")
	idIntSlice, _ := utils.StringSliceToIntSlice(idSlice)
	resp, err := rpc.RoleServiceClient.DeleteRole(context.Background(), &roleServiceV1.DeleteRoleRequest{
		Ids:       idIntSlice,
		DeletedBy: "Kkk",
	})
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}
	ctx.JSON(http.StatusOK, result.Success(resp))
}

func (r *Role) SetRoleStatus(c *gin.Context) {
	result := common.NewResult()
	// 角色ID
	roleId, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, result.Fail(400, "参数错误"))
		return
	}
	// 角色状态
	roleStatus, err := strconv.ParseInt(c.PostForm("status"), 10, 64)
	if roleStatus < 0 || roleStatus > 1 {
		c.JSON(http.StatusOK, result.Fail(400, "状态值不合法"))
		return
	}

	resp, err := rpc.RoleServiceClient.SetRoleStatus(context.Background(), &roleServiceV1.SetRoleStatusRequest{
		Id:        roleId,
		Status:    int32(roleStatus),
		UpdatedBy: "Kkk",
	})
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, result.Success(resp))
}

func (r *Role) CreateRoleInterface(c *gin.Context) {
	result := common.NewResult()
	roleId, err := strconv.ParseInt(c.PostForm("role_id"), 10, 64)
	if err != nil {
		fmt.Printf("roleId err: %s\n", err.Error())
		c.JSON(http.StatusOK, result.Fail(400, "RoleId参数错误"))
		return
	}
	interfaceIds := c.PostForm("interface_ids")
	if strings.TrimSpace(interfaceIds) == "" {
		c.JSON(http.StatusOK, result.Fail(400, "接口ID不能为空"))
		return
	}
	interfaceIdSlice, _ := utils.StringSliceToIntSlice(strings.Split(interfaceIds, ","))

	var in roleServiceV1.RoleBindingInterfaceRequest
	var roleInterfaceDataList []*roleServiceV1.RoleInterfaceData
	for _, item := range interfaceIdSlice {
		roleInterfaceData := &roleServiceV1.RoleInterfaceData{
			RoleId:      roleId,
			InterfaceId: item,
		}
		roleInterfaceDataList = append(roleInterfaceDataList, roleInterfaceData)
	}
	in.Data = roleInterfaceDataList

	res, err := rpc.RoleServiceClient.RoleBindingInterface(context.Background(), &in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, result.Success(res))
}

func (r *Role) GetRoleInterfaceList(c *gin.Context) {
	// 获取参数
	roleId, err := strconv.ParseInt(c.Param("role_id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, common.NewResult().Fail(400, "RoleId参数错误"))
		return
	}

	in := &roleServiceV1.GetRoleInterfaceListRequest{
		RoleId: roleId,
	}
	list, err := rpc.RoleServiceClient.GetRoleInterfaceList(context.Background(), in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, common.NewResult().Fail(code, msg))
		return
	}

	var interfaceIdList []int64
	for _, item := range list.Data {
		interfaceIdList = append(interfaceIdList, item.InterfaceId)
	}

	c.JSON(http.StatusOK, common.NewResult().Success(interfaceIdList))
}

func (r *Role) CreateRoleButton(c *gin.Context) {
	result := common.NewResult()
	roleId, err := strconv.ParseInt(c.PostForm("role_id"), 10, 64)
	if err != nil {
		fmt.Printf("roleId err: %s\n", err.Error())
		c.JSON(http.StatusOK, result.Fail(400, "RoleId参数错误"))
		return
	}
	buttonIds := c.PostForm("button_ids")
	if strings.TrimSpace(buttonIds) == "" {
		c.JSON(http.StatusOK, result.Fail(400, "接口ID不能为空"))
		return
	}
	buttonIdSlice, _ := utils.StringSliceToIntSlice(strings.Split(buttonIds, ","))

	var in roleServiceV1.RoleBindingButtonRequest
	var roleButtonDataList []*roleServiceV1.RoleButtonData
	for _, item := range buttonIdSlice {
		roleButtonData := &roleServiceV1.RoleButtonData{
			RoleId:   roleId,
			ButtonId: item,
		}
		roleButtonDataList = append(roleButtonDataList, roleButtonData)
	}
	in.Data = roleButtonDataList

	res, err := rpc.RoleServiceClient.RoleBindingButton(context.Background(), &in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}

	c.JSON(http.StatusOK, result.Success(res))
}

func (r *Role) GetRoleButtonList(c *gin.Context) {
	// 获取参数
	roleId, err := strconv.ParseInt(c.Param("role_id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, common.NewResult().Fail(400, "RoleId参数错误"))
		return
	}

	in := &roleServiceV1.GetRoleButtonListRequest{
		RoleId: roleId,
	}
	list, err := rpc.RoleServiceClient.GetRoleButtonList(context.Background(), in)
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		c.JSON(http.StatusOK, common.NewResult().Fail(code, msg))
		return
	}

	var interfaceIdList []int64
	for _, item := range list.Data {
		interfaceIdList = append(interfaceIdList, item.ButtonId)
	}

	c.JSON(http.StatusOK, common.NewResult().Success(interfaceIdList))
}

func (r *Role) GetPermCode(c *gin.Context) {
	c.JSON(http.StatusOK, common.NewResult().Success([]string{"100", "200", "300"}))
}
